<?php
/**
 * TinyMVC - TinyMVCViewRenderer.class.php file
 *
 * @author Adrian Wieczorek <adi(at)tinymvc(dot)org>
 * @package TinyMVC
 * @version $Id: TinyMVCViewRenderer.class.php 32 2008-01-03 15:37:36Z adi3ek $
 *
 */

/**
 * Simple view renderer class
 * @package TinyMVC
 *
 */

// TODO: clean&tidy - comments
class TinyMVCViewRenderer {

	private $defaultRootViewName;

	public function __construct($defaultRootViewName = 'tinymvcRootView') {
		$this->defaultRootViewName = $defaultRootViewName;
	}

	/**
	 * render view
	 * @param TinyMVCModelAndView $modelAndView model and view transfer object
	 * @return string response page source
	 */
	public function render(TinyMVCModelAndView $modelAndView, $rootViewName = '') {
		$rootViewName = $rootViewName ? $rootViewName : $this->defaultRootViewName;
		$model = $modelAndView->getModel()->elements;
  $view = $modelAndView->getView();
  if($view instanceof TinyMVCView) {
			// render view
			$mainViewPath = $view->get($rootViewName);
			if($mainViewPath != null) {
				if(file_exists($mainViewPath)) {
					ob_start();
					include($mainViewPath);
				 $content = ob_get_contents();
				 ob_end_clean();

					print $content;
				}
				else {
					// It shouldn't be executed anymore because of TinyMVCView::get() exception support, but never knows...
					throw new TinyMVCException("Unable to load base view: $mainViewPath file not found");
				}
			}
			else {
				throw new TinyMVCException("Undefined base view: $rootViewName");
			}
  }
  else {
  	throw new TinyMVCException("TinyMVCView expected as view.");
  }
	}
}
